package top.cluski.feieprint.service;

import cn.hutool.core.text.StrFormatter;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import top.cluski.feieprint.domain.dto.FeiEPrintErrorContext;


@Service
public class EMailService {
    @Resource
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String emailUsername;

    static final String EMAIL_TEMPLATE = """
            飞鹅打印机打印失败
            - 打印机名称：{}
            - 主要错误：{}
            - 次要错误：{}
            """;

    @Async("myAsync")
    public void sendFeiePrinterError(FeiEPrintErrorContext context) {
        String text = StrFormatter.format(EMAIL_TEMPLATE,
                context.getPrinterName(), context.getMainErrorMessage(), context.getSubErrorMessage());

        this.sendEmail("飞鹅打印机报警", text);
    }

    private void sendEmail(String subject, String text) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(emailUsername);
        simpleMailMessage.setTo(emailUsername);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(text);
        javaMailSender.send(simpleMailMessage);
    }
}
